package com.atguigu.spzx.manager.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.spzx.manager.handler.CategoryExcelListener;
import com.atguigu.spzx.manager.mapper.CategoryMapper;
import com.atguigu.spzx.manager.service.CategoryService;
import com.atguigu.spzx.model.dto.product.CategoryExcelDTO;
import com.atguigu.spzx.model.entity.product.Category;
import com.atguigu.spzx.model.exception.GuiguException;
import com.atguigu.spzx.model.vo.common.Result;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.product.CategoryExcelVo;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author LT
 * @create 2024-03-15-21:31
 */
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    CategoryMapper categoryMapper;


    @Override
    public List<Category> listByPid(Long pid) {
        List<Category> categories = categoryMapper.categoryByParentId(pid);

        if (!CollectionUtils.isEmpty(categories)){
            categories.forEach(category -> {
                int count = categoryMapper.getCountId(category.getId());
                if (count >0) {
                    category.setHasChildren(true);
                }else {
                    category.setHasChildren(false);
                }
            });
        }
        return categories;
    }

    @Override
    public void exportCates(HttpServletResponse response) {
        try {
            String fileName = URLEncoder.encode("分类数据_"+new DateTime().toString("yyyy-MM-dd_HH") +".xlsx" , "UTF-8");
            response.setHeader("content-disposition" , "attachment;filename="+fileName);
            List<CategoryExcelVo> list = categoryMapper.selectAll();
            EasyExcel.write(response.getOutputStream())
                    .head(CategoryExcelDTO.class)
                    .sheet(0)
                    .doWrite(list);
        } catch (Exception e) {
            throw new GuiguException(ResultCodeEnum.FILE_EXPORT_ERROR,e);
        }
    }

    @Override
    public void importCates(MultipartFile file) {
        if (file.isEmpty()){
            throw new GuiguException(ResultCodeEnum.FILE_UPLOAD_ERROR);
        }
        try {
            EasyExcel.read(file.getInputStream())
                    .head(CategoryExcelDTO.class)
                    .registerReadListener(new CategoryExcelListener(categoryMapper))
                    .doReadAll();
        } catch (Exception e) {
            throw new GuiguException(ResultCodeEnum.FILE_UPLOAD_ERROR,e);
        }

    }
}
